package com.hcm.kernel.mvc.ctrl;

import com.hcm.module.Constants;
import com.hcm.module.admin.model.User;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 所有spring controller的基类
 */
public class KernelCtrl {

    private HttpServletRequest request;
    private HttpSession session;

    public String AJAX_RETURN = "common/ajax_return";

    /**
     * 将内容放入session
     * @param key
     * @param value
     */
    public void set(String key,Object value){
        init();
        session.setAttribute(key,value);
    }

    public Object get(String key){
        init();
        return session.getAttribute(key);
    }

    public void setUser(Object user){
        set(Constants.SESSION_USER, user);
    }

    public User getUser(){
        return (User) get(Constants.SESSION_USER);
    }

    private void init(){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes)requestAttributes;
        request = sra.getRequest();
        try{
            Object user = session.getAttribute(Constants.SESSION_USER);
            if(user == null || session == null) session = request.getSession(true);
            else session = request.getSession(false);
        }catch (Exception e) {
            session = request.getSession(true);
        }
    }

    @ExceptionHandler
    public String exception(Exception ex,ModelMap mm) {
        mm.put("error",ex);
        return "common/error";
    }

}
